package impl;

import java.io.BufferedReader;
import java.io.FileInputStream;
import java.io.IOException;
import java.io.InputStreamReader;
import java.io.StringReader;

import javax.xml.bind.JAXBContext;
import javax.xml.bind.JAXBException;
import javax.xml.bind.Unmarshaller;

import dto.CommandDto;
import service.AnalysisXmlService;

/**
 * @author zhangLin
 */
public class AnalysisXmlServiceImpl implements AnalysisXmlService{

    @Override
    public CommandDto analysisXml (String filePath) {
        BufferedReader reader = null;
        StringBuffer content = new StringBuffer();
        try {
            FileInputStream file = new FileInputStream(filePath);
            InputStreamReader inputFileReader = new InputStreamReader(file, "utf-8");
            reader = new BufferedReader(inputFileReader);

            String tempString;
            // 一次读入一行，直到读入null为文件结束
            while ((tempString = reader.readLine()) != null) {
                content.append(tempString);
            }
            reader.close();
        } catch (IOException e) {
            e.printStackTrace();
            return null;
        } finally {
            if (reader != null) {
                try {
                    reader.close();
                } catch (IOException e1) {
                }
            }
        }
        CommandDto commandDto = new CommandDto();
        try {
            JAXBContext context = JAXBContext.newInstance(CommandDto.class);
            Unmarshaller unmarshaller = context.createUnmarshaller();
            commandDto = (CommandDto)unmarshaller.unmarshal(new StringReader(content.toString()));
        } catch (JAXBException e) {
            e.printStackTrace();
        }
        return commandDto;
    }
}
